/**
 * @author KujoMiva
 * @name app.js
 * @desc vuex的app modules
 * @time 2020年04月06日 12:40:49 星期一
 */

import { getOptionsAPI } from '@/api/app';

export default {
    namespaced: true,
    state: {
        scrollY: 0,
        scrollUpdateStack: new Map(),
        clientOptions: [],
        clientHeaderLinks: [],
    },
    mutations: {
        saveScrollY(state, scrollY) {
            state.scrollY = scrollY;
        },
        setScrollUpdateStack(state, callback) {
            state.scrollUpdateStack.set(callback, callback);
        },
        deleteScrollUpadateStack(state, callback) {
            state.scrollUpdateStack.delete(callback);
        },
        saveClientOptions(state, data) {
            state.clientOptions = data;
        },
        saveClientHeaderLinks(state, data) {
            const result = data.find(v => v.name === 'clientHeaderLinks');
            state.clientHeaderLinks = JSON.parse(result.value);
        },
    },
    actions: {
        gloablScrollAction({ commit, state }) {
            const scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
            commit('saveScrollY', scrollY);
            state.scrollUpdateStack.forEach(fun => fun(scrollY));
        },
        scrollUpdateAction({ commit }, callback) {
            commit('setScrollUpdateStack', callback);
        },
        destoryScrollUpdateAction({ commit }, callback) {
            commit('deleteScrollUpadateStack', callback);
        },
        async getClientOptionsAction({ commit }) {
            const { data } = await getOptionsAPI('client');
            commit('saveClientOptions', data);
            commit('saveClientHeaderLinks', data);
        },
    },
};
